package com.example.kotlin.jetpack_compose_by_tutorials

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension

@Composable
fun ConstraintLayoutDemo() {
    var offsetY by remember {
        mutableStateOf(30f)
    }
    val boxSideLengthDp = 1.dp
    val boxSlideLengthPx = with(LocalDensity.current) {
        boxSideLengthDp.toPx()
    }
    val maxValue = -200 * boxSlideLengthPx
    val draggableState = rememberDraggableState {
        offsetY = (offsetY + it).coerceIn(maxValue, 30f)
    }
    ConstraintLayout(
        Modifier
            .background(Color.Black)
            .fillMaxSize()
    ) {
        //这里设置id
        val (imageBox, textField) = createRefs()
        Box(
            modifier = Modifier
                //跟xml的写法一个思路
                .constrainAs(imageBox) {
                    top.linkTo(parent.top)
                    start.linkTo(parent.start)
                    end.linkTo(parent.end)
                    width = Dimension.fillToConstraints
                }
                .fillMaxHeight(0.4f)
        ) {
        }
        Surface(
            Modifier
                .draggable(orientation = Orientation.Vertical, state = draggableState)
                .constrainAs(textField) {
                    top.linkTo(imageBox.bottom, margin = (offsetY / boxSlideLengthPx).dp)
                    start.linkTo(parent.start)
                    end.linkTo(parent.end)
                    bottom.linkTo(parent.bottom)
                    width = Dimension.fillToConstraints
                    height = Dimension.fillToConstraints
                },
            shape = RoundedCornerShape(topStart = 30.dp, topEnd = 30.dp),
            color = Color.White,
            elevation = 5.dp
        ) {}
    }
}